#include "Common.h"
#include "WindowsHeader.h"

namespace Audio
{
	namespace WindowsPlatform
	{
		WindowsVoice::WindowsVoice(IXAudio2SourceVoice* sourcVoice)
			:xaudio2Voice(sourcVoice)
		{
			
		}

		WindowsVoice::~WindowsVoice()
		{
			if(xaudio2Voice != NULL)
			{
				xaudio2Voice->DestroyVoice();
			}
		}		

		void WindowsVoice::Start()
		{			
			HRESULT hr = xaudio2Voice->Start();
			if(AUD_FAILED(hr))
			{
				throw APIFailedException(L"IXAudio2SourceVoice::Start");
			}
			
		}
		void WindowsVoice::Stop()
		{			
			HRESULT hr = xaudio2Voice->Stop();
			if(AUD_FAILED(hr))
			{
				throw APIFailedException(L"IXAudio2SourceVoice::Stop");
			}			
		}

		void WindowsVoice::SubmitData(UINT8* raw, UINT32 size, SubmitBufferType bufferType)
		{
			XAUDIO2_BUFFER buff = {0};
			HRESULT hr;
			buff.pAudioData = raw;
			buff.AudioBytes = size;
			buff.Flags = bufferType == SubmitBuffer_Normal ? 0 : XAUDIO2_END_OF_STREAM;
			buff.pContext = this->userData;

			if(AUD_FAILED(hr = xaudio2Voice->SubmitSourceBuffer(&buff)))
			{
				throw APIFailedException(L"SubmitSourceBuffer");
			}			
		}

		void WindowsVoice::SetUserData(void* pv)
		{
			userData = pv;
		}
		void* WindowsVoice::GetUserData()
		{
			return userData;
		}

		float WindowsVoice::GetVolume()
		{
			float vol;
			xaudio2Voice->GetVolume(&vol);
			return vol;
		}
		void  WindowsVoice::SetVolume(float vol)
		{
			xaudio2Voice->SetVolume(vol);
		}
		
		BOOL  WindowsVoice::IsPlaying()
		{
			return FALSE;
		}
		
		UINT32  WindowsVoice::GetSamplePlayed()
		{
			XAUDIO2_VOICE_STATE stat = {0};
			xaudio2Voice->GetState(&stat);
			return (UINT32)stat.SamplesPlayed;
		}
	}
}